import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    AsyncStorage,
    TextInput,
    FlatList
} from 'react-native';
import {Toast,ModalIndicator} from 'teaset';
import Utils from'../../common/Utils'
import Config from '../../common/Config'
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
export default class FindFriendPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        });
    };
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            searchMsg:'',
            status:0,
            data:[]
        }
    };

    search=()=>{
        let login={
            "token":this.state.token,
            "content":this.state.searchMsg
        };
        fetch(Config.baseApi+'/directories/searchFriend',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(login)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    if(responseJson.data.length>0){
                        this.setState({
                            data:responseJson.data,
                            status:2
                        })
                    }else {
                        if(this.state.searchMsg.length==0){
                            this.setState({
                                status:0,
                                data:responseJson.data
                            })
                        }else {
                            this.setState({
                                status:1
                            })
                        }
                    }
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.titleView}>
                    <View style={styles.textInputView}>
                        <Image
                            style={{marginLeft:17,width:15,height:15}}
                            source={ImageUtil.Search}/>
                        <TextInput
                            ref={ (ref)=>this.phoneTextInput = ref }
                            autoCapitalize={"none"}
                            style={{flex:1,marginLeft:15,fontSize:13}}
                            keyboardType={"numeric"}
                            autoFocus={true}
                            placeholder="请输入查询字"
                            maxLength={11}
                            placeholderTextColor='#9c9c9c'
                            autoCorrect={false}
                            onChangeText={(text)=>{
                                this.setState({
                                    searchMsg:text,
                                },()=>this.search());
                            }}/>
                    </View>
                    <TouchableOpacity onPress={()=>Actions.pop()}>
                        <Text style={{marginLeft:23,color:'#3090dd',fontSize:17,marginTop:34}}>取消</Text>
                    </TouchableOpacity>
                </View>
                {this.isSearching()}
            </View>
        );
    }

    isSearching=()=> {
        if (this.state.status === 0) {
            return null
        } else if (this.state.status === 1) {
            return (
                <View style={{
                    height: 68,
                    width: width,
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop: 15,
                    backgroundColor: '#ffffff'
                }}>
                    <Text style={{fontSize: 14, color: '#646464'}}>该用户不存在</Text>
                </View>
            )
        } else if (this.state.status === 2) {
            return (
                <FlatList
                    keyExtractor={this._keyExtractor}
                    renderItem={this._renderItem}
                    data={this.state.data}/>
            )
        }
    };

    _keyExtractor = (item, index) => item.id;

    _renderItem=(item)=>{
        return (
            <View>
                <TouchableOpacity
                    onPress={() => Actions.DetailsPage({id: item.item.creditId})}
                    style={{
                        height: 68, width: width, alignItems: 'center', flexDirection: 'row',
                        marginTop: 15, backgroundColor: '#ffffff'
                    }}>
                    <Image
                        source={{uri: 'http://118.31.37.236/upload/' + item.item.head}}
                        style={styles.headImg}/>
                    <View style={{marginLeft: 23}}>
                        {item.item.remarkName !== null&&item.item.remarkName!=''
                            ? (<Text style={styles.nameMsg}>{item.item.remarkName}</Text>)
                            : (<Text style={styles.nameMsg}>{item.item.name}</Text>)}
                        <Text style={styles.introductionMsg}>信用号：{item.item.id}</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    };

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#e8e8e8',
        width:width,
        height:64,
        flexDirection:'row'
    },
    textInputView:{
        flexDirection:'row',
        height:29,
        width:329,
        borderRadius:5,
        marginTop:26,
        backgroundColor:'#ffffff',
        alignItems:'center',
        marginLeft:15
    },
    labelBottomView:{
        height:67,
        width:width,
        flexDirection:'row',
        alignItems:'center'
    },
    headImg:{
        height:44,
        width:44,
        borderRadius:5,
        marginLeft:15
    },
    nameMsg:{
        fontSize:13,
        color:'#000000'
    },
    introductionMsg:{
        marginTop:13,
        fontSize:13,
        color:'#646464'
    },
});